package de.hs.rm.jmx;

import java.util.ArrayList;
import java.util.Map;

import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.OpenType;
import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import javax.management.openmbean.TabularType;

public class Pizzeria implements PizzeriaMXBean {
	
	
	private CompositeType ctPizza = null;
	private TabularType ttPizzaMenu = null;
	private final String[] ttPizzaIndexNames = {"name"};
	private final String[] ctPizzaItemNames = {"name", "price", "availability"};
	private final String[] ctPizzaItemDesc = {"pizza name", "pizza price", "availability of pizza"};
	private final OpenType[] ctPizzaItemTypes = {SimpleType.STRING, SimpleType.DOUBLE, SimpleType.BOOLEAN};
	
	ArrayList<Pizza> pizzaMenu = new ArrayList<Pizza>();
	private Pizza examplePizza = new Pizza("Schinken", 5.4, true);
	private TabularDataSupport pizzaMenuSizes = null;
		
	public Pizzeria()
	{
		try
		{
			ctPizza = new CompositeType("pizza","a Pizza", ctPizzaItemNames, ctPizzaItemDesc, ctPizzaItemTypes);
			ttPizzaMenu = new TabularType("pizzaMenuSizes", "Pizzas by Size", ctPizza, ttPizzaIndexNames);
			
		}
		catch (OpenDataException e) {}
		pizzaMenuSizes = new TabularDataSupport(ttPizzaMenu);		
	}

	@Override
	public Pizza getPizzaByName(String name) {
		for(Pizza pizza:pizzaMenu)
		{
			if(name.equals(pizza.getName()))
				return pizza;
		}
		return null;
	}
	
	@Override
	public Pizza getPizzaByName(String name, Double maxPrice) {
		for(Pizza pizza:pizzaMenu)
		{
			if(name.equals(pizza.getName()) && maxPrice < pizza.getPrice())
				return pizza;
		}
		return null;
	}

	@Override
	public void addPizzaToMenu(Pizza pizza) {
		pizzaMenu.add(pizza);
		try {		
			Object[] ctPizzaItemValues = {pizza.getName(),pizza.getPrice(), pizza.isAvailable()};
			CompositeData cdPizza = new CompositeDataSupport(ctPizza, ctPizzaItemNames, ctPizzaItemValues);
			pizzaMenuSizes.put(cdPizza);
			
		} catch (OpenDataException e) {
			System.out.println("Error Adding Pizza");
			e.printStackTrace();
		}
	}

	@Override
	public Pizza[] getPizzaMenu() {
		Pizza[] menu = new Pizza[pizzaMenu.size()];
		for(int i = 0; i < menu.length; i++)
			menu[i] = pizzaMenu.get(i);
		return menu;
	}

//	@Override
//	public TabularData getPizzaMenuSizes() {
//		return (TabularData)pizzaMenuSizes.clone();
//	}

	@Override
	public Pizza getExamplePizza() {
		return examplePizza;
	}

	@Override
	public void setExamplePizza(Pizza pizza) {
		examplePizza = pizza;
		
	}

	@Override
	public void setPizzaMenu(Pizza[] pizzaMenu) {
		this.pizzaMenu = new ArrayList<Pizza>();
		for(int i = 0; i < pizzaMenu.length; i++)
			this.pizzaMenu.add(pizzaMenu[i]);
		
	}

}
